import { defineStore } from 'pinia'
import * as api from '@/apis/user'
import { roles } from '@/utils/config.js'
import Cookies from 'js-cookie'
import { getAreaByCode } from '@/utils/areaQuery.js'
export const usePermissionStore = defineStore('permission', () => {
  const permissions = ref()
  const initLoading = ref(true)
  const initError = ref(false)
  const hasCreateWorkOrderRight = ref(false)
  // center_province_leader 省领导
  // center_city_leader     州市领导
  // center_county_leader   区县领导
  // center_office_leader   处室及直属单位领导
  // center_province_staff  省处置人员
  // center_city_staff      州市处置人员
  // center_county_staff    区县处置人员
  // center_office_staff    处室及直属单位处置人员

  // 用户信息
  const user = reactive({
    name: null,
    phone: null,
    avatar: null,
    areaCode: null,
    areaName: null,
    level: null,
    userCode: null,
    orgCode: null,
    orgName: null,
    roleCode: null,
    innerRoleCode: null
  })
  // 是否有创建权限
  const isCreateRole = ref(() =>
    [roles.provinceStaff, roles.cityStaff].includes(user?.innerRoleCode || '')
  )
  const isStaff = ref(
    [
      roles.provinceStaff,
      roles.cityStaff,
      roles.countryStaff,
      roles.officeStaff
    ].includes(user.innerRoleCode || '')
  )
  const isLeader = ref(
    [
      roles.provinceLeader,
      roles.cityLeader,
      roles.countryLeader,
      roles.officeLeader
    ].includes(user.innerRoleCode || '')
  )
  async function bootstrap() {
    try {
      Cookies.set(
        'X-Token',
        'ZWI0NjlhMGItNTBlNS00ZDNkLWIyOWItNjdlZTdlMzk4ZGIy', //昆明
        { expires: 7 }
      )
      const res = await api.getUserInfo()
      if (res && res.ret === 0) {
        user.name = res.data?.name || res.data?.mobile || ''
        user.phone = res.data?.mobile || ''
        user.areaCode = res.data?.areaCode || ''
        user.areaName = getAreaByCode(res.data?.areaCode || '')
        user.level = res.data?.areaLevel || ''
        user.userCode = res.data?.userCode || ''
        user.orgCode = res.data?.orgCode || ''
        user.orgName = res.data?.orgName
        user.roleCode = res.data?.roleCode || ''
        user.innerRoleCode = res.data?.innerRoleCode || ''
        permissions.value = []
      } else {
        initError.value = true
      }
      initLoading.value = false
    } catch (res) {
      if (res?.errorcode !== 800403) {
        initError.value = true
      }
      permissions.value = []
    }
  }

  function setGlobalLoading(loading) {
    initLoading.value = loading
  }

  return {
    hasCreateWorkOrderRight,
    permissions,
    initLoading,
    initError,
    bootstrap,
    user,
    isLeader,
    isStaff,
    isCreateRole,
    setGlobalLoading
  }
})
